package com.education.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.education.service.edu.entity.Subject;
import com.education.service.edu.entity.excel.ExcelSubjectData;
import com.education.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 读取 Excel的监听器
 * Created by Lance on 2020/06/26 18:44
 */
@Slf4j
@AllArgsConstructor     // 全参构造函数
@NoArgsConstructor      // 无参构造函数
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectMapper subjectMapper;

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        // 读数据
        log.info("从exclude中读取一条记录 {}", excelSubjectData);
        // 读取第一列标题
        String levelOneTitle = excelSubjectData.getLevelOneTitle();
        // 读取第二列标题
        String levelTwoTitle = excelSubjectData.getLevelTwoTitle();
        log.info("第一列 : {}", levelOneTitle);
        log.info("第二列 : {}", levelTwoTitle);
        // 写入数据库
        Subject subjectLevelOneTitle = this.gteByTitle(levelOneTitle);
        String parentId = null;

        // 处理和存入一级列表
        if (subjectLevelOneTitle == null){
            Subject subject = new Subject();
            // 一级类别 [ 设置为0 ]
            subject.setParentId("0");
            subject.setTitle(levelOneTitle);
            subjectMapper.insert(subject);
            // 获取当前一级列表的ID ===> 作为二级列表的父ID
            parentId= subject.getId();
        }else {
            parentId = subjectLevelOneTitle.getId();
        }

        // 处理和存入二级列表
        Subject subjectLevelTwo = this.getSubByTitle(levelTwoTitle, parentId);
        if(subjectLevelTwo == null){
            Subject subject = new Subject();
            subject.setTitle(levelTwoTitle);
            subject.setParentId(parentId);
            subjectMapper.insert(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成");
    }

    /**
     * 判断一级分类是否存在
     * @return  返回 null 表示不存在
     */
    private Subject gteByTitle(String title){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", "0");
        return subjectMapper.selectOne(queryWrapper);
    }
    /**
     * 判断二级分类是否存在
     * @param title
     * @return 返回对象说明存在，返回null说明不存在
     */
    private Subject getSubByTitle(String title, String parentId){

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", title);
        queryWrapper.eq("parent_id", parentId);
        return subjectMapper.selectOne(queryWrapper);
    }

}
